package cn.edu.djtu.fw.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.djtu.fw.dao.UserMapper;
import cn.edu.djtu.fw.model.User;
import cn.edu.djtu.fw.service.UserServiceI;
import cn.edu.djtu.fw.util.Encrypt;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service(value = "userService")
public class UserServerImpl implements UserServiceI {
	private UserMapper userMapper;

	public UserMapper getUserMapper() {
		return userMapper;
	}

	@Autowired
	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public boolean delete(Integer uid) {
		try {
			userMapper.deleteByPrimaryKey(uid);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public boolean insert(User user) {
		try {
			user.setPwd(Encrypt.e(user.getPwd()));
			userMapper.insert(user);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public boolean insertSelective(User user) {
		try {
			user.setPwd(Encrypt.e(user.getPwd()));
			userMapper.insertSelective(user);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public User getUserById(Integer uid) {
		try {
			return userMapper.selectByPrimaryKey(uid);
		} catch (Exception e) {
		}
		return null;
	}

	@Override
	public boolean updateSelective(User user) {
		try {
			if (user.getPwd()!=null) {
				user.setPwd(Encrypt.e(user.getPwd()));
			}
			userMapper.updateByPrimaryKeySelective(user);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public boolean update(User user) {
		try {
			user.setPwd(Encrypt.e(user.getPwd()));
			userMapper.updateByPrimaryKey(user);
			return true;
		} catch (Exception e) {
		}
		return false;
	}

	@Override
	public Map<String, Object> getAllUser(int page, int rows, User user) {
		try {
			PageHelper.startPage(page, rows);
			List<User> users = userMapper.getAllUser(user);
			Map<String, Object> userMap = new HashMap<String, Object>();
			userMap.put("rows", users);
			userMap.put("total", ((Page<User>) users).getTotal());
			return userMap;
		} catch (Exception e) {
		}
		return null;
	}

	@Override
	public User login(User user) {
		try {
			user.setPwd(Encrypt.e(user.getPwd()));
			return userMapper.selectByNameAndPwd(user);
		} catch (Exception e) {
		}
		return null;
	}
}
